package cn.itcast.handler;

import cn.itcast.message.GroupCreateRequestMessage;
import cn.itcast.message.GroupCreateResponseMessage;
import cn.itcast.server.session.Group;
import cn.itcast.server.session.GroupSession;
import cn.itcast.server.session.GroupSessionFactory;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

import java.util.List;

/**
 * @Name: GroupCreateRequestMessageHandler
 * @Description:
 * @Author: Mr.Tong
 */
@ChannelHandler.Sharable
public class GroupCreateRequestMessageHandler extends SimpleChannelInboundHandler<GroupCreateRequestMessage> {

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, GroupCreateRequestMessage msg) throws Exception {

        //获取群组管理器
        GroupSession groupSession = GroupSessionFactory.getGroupSession();
        //创建群组-如果存在群名对应的群组，则直接返回群组，如果不存在就会创建群名对应的群组，并且返回null
        Group group = groupSession.createGroup(msg.getGroupName(), msg.getMembers());

        if (group == null) {//创建成功
            //向创建者发送创建成功的消息
            ctx.channel().writeAndFlush(new GroupCreateResponseMessage(true, msg.getGroupName() + "创建成功"));
            //向群组的其他人发送消息-被拉入群中

            List<Channel> membersChannel = groupSession.getMembersChannel(msg.getGroupName());
            membersChannel.forEach(channel -> channel.writeAndFlush(new GroupCreateResponseMessage(true, "您已经被拉入" + msg.getGroupName())));
        } else {
            //向创建者发送创建失败的消息
            ctx.channel().writeAndFlush(new GroupCreateResponseMessage(false, msg.getGroupName() + "已经存在"));
        }
    }
}
